import Cookies from 'js-cookie';
import Cache from '@/lib/cache';

const TOKENKEY = 'vue_admin_template_token';
const TOKENTYPEKEY = 'tokenType';
const LANGUAGEKEY = 'language';
const ROLESKEY = 'role';
const USERINFOKEY = 'userInfo';
const LOGINERROR = 'login.error'; // 登录错误的报错信息
const LOGINERROR_USER = 'login.error.user';
const LOGINERROR_PASSWORD = 'login.error.password';
const LOGINERROR_TENANTID = 'login.error.tenantId';
const COOKIETENANT = '__tenant'; // 租户id
const TENANTID = 'tenantId';
const OIDCUSER = 'oidc_user'; // oidc 数据
// 当前机构id
const CURRENT_OU = 'current_ou';
// 赛事执行id
const COMPETITIONTOKEN = 'CompetitionToken';
// 微信绑定错误
const WXERROR = 'register.error';
const WXERROR_PHONENUMBER = 'register.error.phoneNumber';
const WXERROR_TENANTID = 'register.error.tenantId';

export function getUserToken () {
  return new Promise((resolve, reject) => {
    const user = getOidcUser();
    const token = getLocalToken() ? getLocalToken() : user ? user.access_token : getToken();
    const token_type = user ? user.token_type : getLocalTokentype() ? getLocalTokentype() : 'Bearer';
    setToken(token);
    setTokenType(token_type);
    resolve(token);
  });
}

export function setOidcUser (user) {
  Cache.set(OIDCUSER, user);
}

export function getOidcUser () {
  return Cache.get(OIDCUSER);
}

/* token 缓存 */
export function getToken () {
  const token = Cookies.get(TOKENKEY);
  if (token) {
    return token;
  } else if (Cache.get(TOKENKEY)) {
    setToken(Cache.get(TOKENKEY));
    return Cache.get(TOKENKEY);
  } else {
    return '';
  }
  // return Cookies.get(TOKENKEY) ? Cookies.get(TOKENKEY) : Cache.get(TOKENKEY);
}

export function getLocalToken () {
  return Cache.get(TOKENKEY);
}

export function setToken (token) {
  Cache.set(TOKENKEY, token);
  return Cookies.set(TOKENKEY, token);
}

export function removeToken () {
  // localStorage.removeItem(TOKENKEY);
  Cache.clear(TOKENKEY);
  return Cookies.remove(TOKENKEY);
}
/* tokentype 缓存 */
export function getLocalTokentype () {
  return Cache.get(TOKENTYPEKEY);
}

export function setTokenType (aTokenType) {
  Cache.set(TOKENTYPEKEY, aTokenType);
}

export function removeTokenType () {
  Cache.clear(TOKENTYPEKEY);
}

/**
 * 获取语言
 */
export function getLanguage () {
  return Cookies.get(LANGUAGEKEY);
}

/**
 * 设置语言
 * @param {string} language 语言
 */
export function setLanguage (language) {
  return Cookies.set(LANGUAGEKEY, language);
}
/**
 * 获取权限列表
 */
export function getRoles () {
  // const lRo = localStorage.getItem(ROLESKEY);
  const lRo = Cache.get(ROLESKEY);
  return lRo || [];
}
/**
 * 设置权限列表
 * @param {array | null} roles 权限列表
 */
export function setRoles (roles) {
  Cache.set(ROLESKEY, roles);
  // localStorage.setItem(ROLESKEY, roles ? JSON.stringify(roles) : '');
}
/**
 * 删除权限列表
 */
export function deleteRoles () {
  // localStorage.removeItem(ROLESKEY);
  Cache.clear(ROLESKEY);
}
/**
 * 保存用户信息
 */
export function setUserInfo (info) {
  Cache.set(USERINFOKEY, info);
}
/**
 * 获取用户信息
 */
export function getUserInfo () {
  return Cache.get(USERINFOKEY);
}
/**
 * 删除用户信息
 */
export function removeUserInfo () {
  Cache.clear(USERINFOKEY);
}
/** 登录
 * 获取登录错误信息
 */
export function getLoginError () {
  let errorCode = '';
  switch (Cookies.get(LOGINERROR)) {
    case 'Success': // 登录;
      errorCode = { msg: '登录成功', code: Cookies.get(LOGINERROR) };
      break;
    case 'UserNotFound':
      errorCode = { msg: '未找到该用户', code: Cookies.get(LOGINERROR) };
      break;
    case 'NotAllowed': // 登录;
      errorCode = { msg: '不允许登录', code: Cookies.get(LOGINERROR) };
      break;
    case 'LockedOut': // 登录;
      errorCode = { msg: '用户被锁定（登录失败次数太多）', code: Cookies.get(LOGINERROR) };
      break;
    case 'RequiresTwoFactor': // 登录;
      errorCode = { msg: '需要二次验证登录', code: Cookies.get(LOGINERROR) };
      break;
    case 'Disabled':
      errorCode = { msg: '用户被禁用', code: Cookies.get(LOGINERROR) };
      break;
    case 'InvalidPassword':
      errorCode = { msg: '密码不正确', code: Cookies.get(LOGINERROR) };
      break;
    case 'TenantDisabled':
      errorCode = { msg: '租户被禁用', code: Cookies.get(LOGINERROR) };
      break;
    case 'TenantNotFound':
      errorCode = { msg: '未找到该租户', code: Cookies.get(LOGINERROR) };
      break;
    case 'InvalidVerificationCode':
      errorCode = { msg: '验证码错误', code: Cookies.get(LOGINERROR) };
      break;
    case 'OrganizationUnitDisabled':
      errorCode = { msg: '组织机构被禁用', code: Cookies.get(LOGINERROR) };
      break;
    default:
  }
  return errorCode;
}
/** 登录
 * 清除登录错误信息
 */
export function deleteLoginError () {
  Cookies.remove(LOGINERROR);
}
/** 登录
 * 获取登录错误的用户信息
 */
export function getLoginErrorUserMsg () {
  const msg = {
    user: Cookies.get(LOGINERROR_USER) ? Cookies.get(LOGINERROR_USER) : '',
    password: Cookies.get(LOGINERROR_PASSWORD) ? Cookies.get(LOGINERROR_PASSWORD) : '',
    tenantId: Cookies.get(LOGINERROR_TENANTID) ? Cookies.get(LOGINERROR_TENANTID) : ''
  };
  return msg;
}
/** 登录
 * 清除登录错误的用户信息
 */
export function deleteLoginErrorUserMsg () {
  Cookies.remove(LOGINERROR_USER);
  Cookies.remove(LOGINERROR_PASSWORD);
  Cookies.remove(LOGINERROR_TENANTID);
}

export function setCookieTenant (aData) {
  const _data = aData || '';
  Cache.set(COOKIETENANT, _data);
  return Cookies.set(COOKIETENANT, _data);
}

export function getCookieTenant () {
  return Cache.get(COOKIETENANT);
}

export function removeCookieTenant () {
  Cache.clear(COOKIETENANT);
  return Cookies.remove(COOKIETENANT);
}

export function setTenantId (adata) {
  Cache.set(TENANTID, adata);
}

export function getTenantId (adata) {
  return Cache.get(TENANTID);
}

export function deleteTenantId (adata) {
  Cache.clear(TENANTID);
}

// 微信绑定注册
export function getWxRegisterError () {
  let errorCode = '';
  const _getcookies_code = Cookies.get(WXERROR);
  switch (_getcookies_code) {
    case 'Success': // 登录;
      errorCode = { msg: '登录成功', code: _getcookies_code };
      break;
    case 'UserNotFound':
      errorCode = { msg: '未找到该用户', code: _getcookies_code };
      break;
    case 'NotAllowed': // 登录;
      errorCode = { msg: '不允许登录', code: _getcookies_code };
      break;
    case 'LockedOut': // 登录;
      errorCode = { msg: '用户被锁定（登录失败次数太多）', code: _getcookies_code };
      break;
    case 'RequiresTwoFactor': // 登录;
      errorCode = { msg: '需要二次验证登录', code: _getcookies_code };
      break;
    case 'Disabled':
      errorCode = { msg: '用户被禁用', code: _getcookies_code };
      break;
    case 'InvalidPassword':
      errorCode = { msg: '密码不正确', code: _getcookies_code };
      break;
    case 'TenantDisabled':
      errorCode = { msg: '租户被禁用', code: _getcookies_code };
      break;
    case 'TenantNotFound':
      errorCode = { msg: '未找到该租户', code: _getcookies_code };
      break;
    case 'InvalidVerificationCode':
      errorCode = { msg: '验证码错误', code: _getcookies_code };
      break;
    case 'OrganizationUnitDisabled':
      errorCode = { msg: '组织机构被禁用', code: _getcookies_code };
      break;
    default:
  }
  return errorCode;
}

/** 微信绑定注册
 * 清除微信绑定注册错误信息
 */
export function deleteWxRegisterError () {
  Cookies.remove(WXERROR);
}
/** 微信绑定注册
 * 获取微信绑定注册错误的手机号
 */
export function getWxRegisterErrorMsg () {
  const msg = {
    phoneNumber: Cookies.get(WXERROR_PHONENUMBER) || '',
    tenantId: Cookies.get(WXERROR_TENANTID) || ''
  };
  return msg;
}
/** 微信绑定注册
 * 清除微信绑定注册错误的手机号
 */
export function deleteWxRegisterErrorMsg () {
  Cookies.remove(WXERROR_PHONENUMBER);
  Cookies.remove(WXERROR_TENANTID);
}
/**
 * 保存当前机构id
 */
export function setCurrentOU (aOUID) {
  Cache.set(CURRENT_OU, aOUID);
}
/**
 * 获取当前机构id
 */
export function getCurrentOU () {
  return Cache.get(CURRENT_OU);
}
/**
 * 清除当前机构id
 */
export function removeCurrentOU () {
  return Cache.clear(CURRENT_OU);
}
/**
 * 赛事执行
 */
export function SetCompetitionToken (aOUID) {
  Cache.set(COMPETITIONTOKEN, aOUID);
}
/**
 * 获取当前赛事执行
 */
export function getCompetitionToken () {
  return Cache.get(COMPETITIONTOKEN);
}
